package org.admin.entity.dto;

import core.validate.Rule;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.admin.entity.BaseDto;
import org.admin.service.RedisService;

@EqualsAndHashCode(callSuper = true)
@Data
public class EntryDto extends BaseDto<EntryDto> {

    public EntryDto(){
        addRule(new Rule<?>[] {
                Rule.String("username")
                        .between(5, 16, "用户名称长度错误"),
                Rule.String("password")
                        .between(6, 32, "用户密码长度错误")
                        .regex("^[0-9a-zA-Z-_]+$", "用户密码格式不正确"),
                Rule.Boolean("always")
                        .setMessages("非法数据"),
                Rule.String("token")
                        .length(32, "令牌格式不正确")
                        .regex("^[0-9a-fA-F]{32}$", "令牌格式不正确")
                //.length(36, "令牌格式不正确")
                //.regex("^[0-9a-zA-Z]{8}(-[0-9a-zA-Z]{4}){3}-[0-9a-zA-Z]{12}$", "令牌格式不正确")
        });

    }
    public EntryDto(RedisService redisService){
        this();
        addRule(new Rule<?>[] {
                Rule.String("captcha")
                        .length(4, "验证码格式不正确")
                        .test(holder -> {
                            String captcha = holder.getValue();
                            String key = holder.getOrigin("key");
                            String token = holder.getOrigin("token");

                            if(redisService.getItem(token + "/" + key).equals(captcha.toLowerCase())){
                                redisService.remove(token + "/" + key);
                                return true;
                            }
                            return false;

                        }, "验证码错误"),
                Rule.String("key")
                        .length(36, "验证码密钥不正确"),
        });
    }

    protected EntryDto inst(){
        return this;
    }

    private String token;
    private String username;
    private String password;
    private Boolean always;
}
